<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="关键字" prop="name" label-width="68px">
        <el-input v-model="queryParams.name" placeholder="商品、编号、场馆" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="场馆" prop="venueId" label-width="68px">
        <el-select v-model="queryParams.venueId" placeholder="场馆选择" clearable filterable style="width: 140px">
          <el-option v-for="dict in this.venueList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" prop="isPutaway">
        <el-select v-model="queryParams.isPutaway" clearable style="width: 140px">
          <el-option v-for="dict in this.putawayStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="场次" prop="abToday" label-width="68px">
        <el-select v-model="queryParams.abToday" placeholder="场次" clearable style="width: 140px" @clear="clearAbToday">
          <el-option v-for="dict in this.abToday" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="回收状态" prop="belonging">
        <el-select v-model="queryParams.belonging" placeholder="回收" clearable style="width: 140px">
          <el-option v-for="dict in this.belonging" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="止售区域" prop="resellStatus">
        <el-select v-model="queryParams.resellStatus" placeholder="止售区域" clearable style="width: 140px">
          <el-option v-for="dict in this.resellStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="止售日期" v-show="isShowDate">
        <el-date-picker v-model="dateRange" style="width: 340px" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm:ss">
          ></el-date-picker>
      </el-form-item>
      <el-form-item label="止售情况" prop="endState">
        <el-select v-model="queryParams.endState" placeholder="止售情况" clearable style="width: 140px">
          <el-option v-for="dict in this.endStateList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态" prop="isResell">
        <el-select v-model="queryParams.isResell" placeholder="商品状态" clearable style="width: 140px">
          <el-option v-for="dict in this.isResellList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="现金价" prop="startPrice">
        <el-input v-model="queryParams.startPrice" placeholder="" clearable style="width: 80px" />
        -
        <el-input v-model="queryParams.endPrice" placeholder="" clearable style="width: 80px" />
      </el-form-item>
      <el-form-item label="最新价" prop="startPrice">
        <el-input v-model="queryParams.startLatestPrice" placeholder="" clearable style="width: 80px" />
        -
        <el-input v-model="queryParams.endLatestPrice" placeholder="" clearable style="width: 80px" />
      </el-form-item>

      <!-- <el-form-item prop="endPrice">
        <el-input v-model="queryParams.endPrice" placeholder="结束价格" clearable style="width: 113px" />
      </el-form-item> -->
      <el-form-item label="创建时间">
        <el-date-picker v-model="createDateRange" style="width: 340px" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm:ss">
          ></el-date-picker>
      </el-form-item>

      <el-form-item label="交易日期">
        <el-date-picker v-model="queryParams.showDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 150px">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['showroom:lot:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="this.queryParams.isPutaway == 0" type="success" plain size="mini" @click="changeLotStatus" v-hasPermi="['showroom:lot:batchUp']">一键上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="this.queryParams.isPutaway == 1" type="danger" plain size="mini" @click="changeLotStatus" v-hasPermi="['showroom:lot:batchUp']">一键下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="exportExcel" v-hasPermi="['showroom:lot:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :height="tableHeight" ref="elTable" @sort-change="changeTableSort" v-loading="loading" :data="goodsList" :row-key="getRowKeys" @selection-change="handleSelectionChange" @row-dblclick="handleUpdate" stripe border>
      <el-table-column v-if="this.queryParams.isPutaway" type="selection" :reserve-selection="true" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="商品名称" prop="name" width="200" :sortable="'custom'" />
      <el-table-column label="商品编号" prop="goodsNo" width="150" align="center" :sortable="'custom'" />
      <el-table-column label="场馆名称" prop="venueInfo.name" width="120" align="center" />
      <el-table-column label="成本价(元)" :sortable="'custom'" prop="costPrice" width="120" align="center" v-if="checkPermi(['showroom:look:price'])" />
      <el-table-column label="现金价格(元)" :sortable="'custom'" prop="cashPrice" width="120" align="center" />
      <el-table-column label="金积分价格" :sortable="'custom'" prop="goldPrice" width="120" align="center" />
      <el-table-column label="银积分价格" :sortable="'custom'" prop="silverPrice" width="120" align="center" />
      <el-table-column label="是否上架" prop="isPutaway" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_putaway_status" :value="scope.row.isPutaway" />
        </template>
      </el-table-column>
      <el-table-column label="商品状态" prop="isResell" width="120" align="center" :sortable="'custom'">
        <template slot-scope="scope">
          {{selectDictLabel(isResell,scope.row.isResell)}}
        </template>
      </el-table-column>
      <el-table-column label="兑换状态" prop="artConvertState" width="120" align="center" :sortable="'custom'">
        <template slot-scope="scope">
          {{selectDictLabel(artConvertState,scope.row.artConvertState)}}
        </template>
      </el-table-column>
      <el-table-column label="竞价品类型" width="180" align="center" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.secCode=='AUCTION'">普通竞价品</span>
          <span v-if="scope.row.secCode=='PICKUP'">提货竞价品</span>
        </template>
      </el-table-column>
      <el-table-column label="止售次数" :sortable="'custom'" prop="resellNum" width="120" align="center" v-if="checkPermi(['lot:look:resellNum'])" />
      <el-table-column v-if="checkPermi(['lot:look:totalResellNum'])" label="转售次数" sortable prop="totalResellNum" width="120" align="center" />
      <el-table-column label="最新价" width="120" prop="latestPrice" align="center" :sortable="'custom'">
        <template slot-scope="scope">
          <span>{{scope.row.latestPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column label="止售价" width="120" prop="latestPrice" align="center" :sortable="'custom'">
        <template slot-scope="scope">
          <span v-if="scope.row.isResell==2">{{scope.row.latestPrice}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="止售时间" width="180" align="center" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.isResell==2">{{scope.row.endTime}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="缩略图" prop="imgMin" align="center" width="200">
        <template slot-scope="scope">
          <table-image :imgDicUrls="scope.row.imgMin"></table-image>
        </template>
      </el-table-column> -->
      <el-table-column label="大图" prop="minList" align="center" width="200">
        <template slot-scope="scope">
          <table-image :imgDicUrls="scope.row.minList"></table-image>
        </template>
      </el-table-column>
      <el-table-column label="排序" sortable prop="orderNum" width="80" align="center" />
      <el-table-column label="创建时间" sortable prop="createTime" width="180" align="center" />
      <el-table-column label="操作" fixed="right" align="center" width="180">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isPutaway == 1" size="mini" type="text" icon="" @click.stop="batchUp(scope.row)" v-hasPermi="['showroom:lot:batchUp']">下架</el-button>
          <!-- 今天场或明天场&&机器人回收 -->
          <div v-else>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['showroom:lot:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="copyGoods(scope.row)" v-hasPermi="['showroom:lot:edit']">复制商品</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleDelete(scope.row)" v-hasPermi="['showroom:lot:remove']">删除</el-button>
            <el-button v-if="queryParams.belonging == 1" size="mini" type="text" icon="" @click.stop="openABChange(scope.row)" v-hasPermi="['showroom:lot:turnAb']">转场</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-row type="flex" class="row-bg" justify="space-between">
      <el-col :span="4">
        <span v-if="this.queryParams.isPutaway !== undefined" style="line-height:60px">已选中:{{this.batchUpParams.ids.length}}</span>
      </el-col>
      <el-col :span="16">
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 新建竞价品 -->
    <div v-if="open">
      <Z-Dialog :title="title" :visible.sync="open" @confirm="submitForm('formView')" @cancel="open=false">
        <form-view :formData="form" :lotVenueList="lotVenueList" :venueList="venueList" ref="formView"></form-view>
      </Z-Dialog>
    </div>

    <div v-if="openAB">
      <Z-Dialog :title="title" :visible.sync="openAB" @confirm="postSaveGoodsTurnAb()" @cancel="open=false">
        <el-form ref="abForm" :model="abForm" label-width="150px" :rules="rules">
          <el-form-item label="场次" prop="abToday">
            <el-select v-model="abForm.abToday" placeholder="场次选择" clearable class="input-W">
              <el-option v-for="dict in this.abTodayEnd" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </Z-Dialog>
    </div>

  </div>
</template>

<script>
import { listGoodsInfo, addGoodsInfo, batchUpGoodsInfo, editGoodsInfo, delGoodsInfo, saveGoodsTurnAb } from "@/api/showroom/goods";
import { listVenue } from "@/api/showroom/venue";
import tableImage from "@/components/TableImageView/index.vue";
import { goodsPayTypeEnum } from '@/common/enums'
import { excelExportApi } from '@/api/filer'
import formView from "./formView.vue";
import { deepClone } from '@/utils/index'
import { checkPermi } from "@/utils/permission"; // 权限判断函数
import hasPer from "@/directive/permission/hasPer.js";
import { getDateTime, compare } from "@/utils/index"

export default {
  name: "Lot", //竞价品信息
  components: { tableImage, formView },
  dicts: [
    "goods_isResell_status",
    "goods_putaway_status",
  ],
  data() {
    return {
      goodsPayTypeEnum,
      //是否显示止售日期搜索框
      isShowDate: false,
      openAB: false,
      //上传的图片
      dialogImageUrl: "",
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      goodsList: [], //商品列表
      venueList: [], //场馆列表
      dateRange: [], //日期区间
      createDateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示添加弹窗
      add_open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: this.global.pageSize,
        typeCode: 1,
        name: undefined,
        resellStatus: undefined,
        isPutaway: undefined,
        startPrice: undefined,
        endPrice: undefined,
        isResell: undefined,
        venueId: undefined
      },
      pageNum: 1,
      turnAbParams: {},
      // 表单参数
      form: {},
      abForm: {},
      typeList: [
        { label: "竞价品", value: 1 },
        { label: "兑换商品", value: 4 },
      ],

      artConvertState: [
        { label: "未兑换", value: 0 },
        { label: "已兑换", value: 1 },
      ],

      resellStatus: [
        { label: "止售区竞价品", value: 'AUCTION' },
        { label: "提货竞价品", value: 'PICKUP' },
        // { label: "已止售", value: 2 },
      ],
      isResell: [{ label: '未被抢购', value: 0 }, { label: '已被抢购', value: 1 }, { label: '已止售', value: 2 }],
      endState: [{ label: '止售提货', value: 1 }, { label: '止售置换', value: 2 }, { label: '止售转场', value: 3 }],
      abToday: [
        { label: getDateTime(0), value: 0 },
        { label: getDateTime(1), value: 1 },
        { label: getDateTime(2), value: 2 },
      ],

      abTodayEnd: [
        { label: getDateTime(1), value: 1 },
        { label: getDateTime(2), value: 2 },
      ],

      belonging: [{ label: "机器人回收", value: 1 }, { label: "非机器人回收", value: 0 }],

      batchUpParams: {
        ids: [],
        isPutaway: undefined
      },
      rules: {
        abToday: [{ required: true, message: "转场", trigger: "blur" }],
      },
      lotVenueList: []
    };
  },
  watch: {
    "queryParams.resellStatus": {
      deep: true,
      handler: function (newV, oldV) {
        this.isShowDate = newV == "zp" ? true : false;
      },
    },

    "queryParams.isPutaway": {
      deep: true,
      handler: function (newV, oldV) {
        this.batchUpParams.isPutaway = newV == 1 ? 0 : 1; //上下架取反
        this.batchUpParams.ids = [];
      },
    },

    "queryParams": {
      deep: true,
      handler: function (newV, oldV) {
        if (this.pageNum == newV.pageNum) {
          this.handleQuery();
        } else {
          this.pageNum = newV.pageNum;
        }
      },
    },
    createDateRange(newV, oldV) {
      if (newV) {
        if (newV.length >= 2) {
          this.queryParams.createTimeStart = String(newV[0]);
          this.queryParams.createTimeEnd = String(newV[1]);
        }
      }
      else {
        this.queryParams.createTimeStart = undefined;
        this.queryParams.createTimeEnd = undefined;
      }
      this.getList();
    },
  },
  computed: {
    tableHeight() {
      return 'calc(100vh - 330px)'
    },
    endStateList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.endState));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    isResellList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.isResell));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    //状态列表添加全部
    goodsTypeList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.typeList));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    //转售状态添加全部
    resellAllList() {
      let typeDictArray = JSON.parse(
        JSON.stringify(this.resellStatus)
      );
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    //止售区域状态
    resellStatusList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.resellStatus));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    //上架状态
    putawayStatusList() {
      let typeDictArray = JSON.parse(
        JSON.stringify(this.dict.type.goods_putaway_status)
      );
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },

    //是否兑换
    artConvertStateList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.artConvertState));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },

  },
  created() {
    this.getList();
    this.getVenueList();
  },
  methods: {
    checkPermi,
    getList() {
      this.loading = true;
      listGoodsInfo(this.queryParams)
        .then((response) => {
          if (response.code == 200) {
            this.goodsList = response.data;
            this.total = response.total;
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    changeTableSort(column) {
      this.queryParams.orderBy = column.prop;
      this.queryParams.isAsc = (column.order == 'descending' ? 0 : 1); //ascending == 升序 descending == 降序  0 倒,1正
      this.getList();
    },
    /**获取场馆列表 */
    getVenueList() {
      listVenue(this.queryParams)
        .then((response) => {
          if (response.code == 200) {

            let list = response.data;
            // list.sort(compare('id', true));

            this.lotVenueList = list.filter((item, index, arr) => {
              return item.venueType == 0;
            })

            this.venueList = this.lotVenueList;
          }
        })
        .catch((err) => { });
    },

    //复制商品
    copyGoods(row) {

      this.$store.commit('SETCOPYGOODS', {
        name: row.name,
        minList: row.minList,
        details: row.details
      })
      this.$modal.msgSuccess("复制成功");
    },


    //列表选中
    handleSelectionChange(val) {
      this.batchUpParams.ids = val.map((item) => {
        return item.id;
      });
    },

    getRowKeys(row) {
      return row.id
    },

    //下架
    batchUp(row) {
      this.batchUpParams.ids = [row.id];
      this.batchUpParams.isPutaway = 0;
      this.$modal
        .confirm('是否确认下架商品编号"' + row.goodsNo + '的商品"？')
        .then(() => {
          this.changeLotStatus();
        }
        );
    },

    /**一键上下架 */
    changeLotStatus() {
      if (!this.batchUpParams.ids) {
        this.$modal.msgError("请选择需要操作的商品");
        return;
      }
      batchUpGoodsInfo(this.batchUpParams).then((response) => {
        this.$modal.msgSuccess("操作成功");
        this.queryParams.isPutaway = undefined;
        this.batchUpParams.ids = [];
        this.$refs.elTable.clearSelection();

        this.getList();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      // this.resetForm("form");
      this.form = {};
      this.abForm = {};
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.endPrice = undefined;
      this.queryParams.createDateRange = undefined;
      this.queryParams.createTimeStart = undefined;
      this.createDateRange = undefined;
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加竞价品";
    },

    clearAbToday() {
      this.queryParams.abToday = undefined;
    },

    /**上传数据 */
    uploaded(params, dict) {
      this.form[params] = JSON.stringify(dict);
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!hasPer.isPerShow(['showroom:lot:edit'])) {
        return;
      }

      this.reset();
      this.title = "编辑竞价品";
      this.form = deepClone(row);
      this.form.isPutaway = String(this.form.isPutaway);
      this.form.payType = String(this.form.payType);
      // this.form.artVenues = String(this.form.artVenues);
      this.open = true;
    },

    /** 提交按钮 */
    submitForm(refStr) {
      let ref = this.$refs[refStr];
      let valueData = ref.$refs.editor.currentValue;
      let params = ref.form;

      params.details = valueData;
      params.imgMin = params.minList;

      ref.$refs["form"].validate((valid) => {
        if (valid) {
          if (params.id != undefined) {
            editGoodsInfo(params).then((response) => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsInfo(params).then((response) => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    openABChange(row) {
      this.abForm = row;
      this.openAB = true;
      this.title = "转场";
    },

    //转场
    postSaveGoodsTurnAb(row) {
      let params = {
        "goodsId": this.abForm.id,
        "venueId": this.abForm.venueId,
        "orderResellId": this.abForm.orderResellId,
        "abToday": this.abForm.abToday,
        "belonging": 1,
        "applyState": 1
      };
      this.$refs["abForm"].validate((valid) => {
        if (valid) {
          saveGoodsTurnAb(params).then((response) => {
            this.$modal.msgSuccess("转场");
            this.openAB = false;
            this.getList();
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除商品编号为"' + row.goodsNo + '"的数据项？')
        .then(() => {
          delGoodsInfo({ goodsInfoId: row.id }).then((response) => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        }
        ).catch(() => { });
    },

    /** 导出按钮操作 */
    exportExcel() {
      this.queryParams.beanName = 'GoodsInfoExport',
        this.queryParams.fileName = '竞价品',
        this.$alert('需要导出 "' + this.total + '" 条数据,是否确认导出', '提示', {
          confirmButtonText: '确定',

        }).then(() => {
          excelExportApi(this.queryParams, '/pms');
        });
    },
  },
};
</script>
<style scoped>
.el-dialog-div {
  height: 60vh;
  overflow: auto;
}
.input-W {
  width: 100%;
}
</style>
